package main.java.com.negromotad.genetics.rules;

import java.util.ArrayList;
import java.util.List;

import main.java.com.negromotad.genetics.TMChromosome;

import org.jgap.IChromosome;
import org.jgap.InvalidConfigurationException;
import org.jgap.NaturalSelector;
import org.jgap.Population;

public class TMRuleSelector extends NaturalSelector {

	/**
	 * The chromosomes pool
	 */
	private List<IChromosome> pool;

	private List<String> genes;

	private List<TMRule> rules;

	/**
	 * Auto generated ID
	 */
	private static final long serialVersionUID = 3785098181795927453L;

	public TMRuleSelector(List<String> genes, List<TMRule> rules) {
		pool = new ArrayList<IChromosome>();
		this.genes = genes;
		this.rules = rules;
	}

	public void select(int arg0, Population origin, Population destination) {
		for (IChromosome chrome : origin.getChromosomes()) {
			try {
				boolean result = evaluateChromosome(new TMChromosome(origin
						.getConfiguration(), genes, chrome));
				if (result) {
					destination.addChromosome(chrome);
				}
			} catch (InvalidConfigurationException e) {
				// Unable to create TMChromsome. Excluded from the population.
				e.printStackTrace();
			}
		}
	}

	public boolean evaluateChromosome(TMChromosome chromosome) {
		for (TMRule rule : rules) {
			if (!rule.evaluate(chromosome.getChromosome())) {
				return false;
			}
		}
		return true;
	}

	@Override
	protected void add(IChromosome arg0) {
		this.pool.add(arg0);
	}

	@Override
	public void empty() {
		this.pool.clear();
	}

	@Override
	public boolean returnsUniqueChromosomes() {
		return false;
	}
}
